package cn.wolfcode.wolf2w.resolver;


import cn.wolfcode.wolf2w.annotation.UserParams;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by 甘静斌 on 2020-08-15 17:38
 */

//定义参数解析器
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private IUserInfoRedisService userInfoRedisService;
    @Override
    public boolean supportsParameter(MethodParameter parameter) {

        /*
            UserInfoArgumentResolver类中的suppersParameter方法中的判断出错了,hasMethodAnntation是判断
            映射方法上有没有贴注解的 , 而UserParams是贴在了映射方法的参数上的,所以在suppersParameter
            方法中最终判断的结果是false,不会执行下面的resolveArgument方法hasParameterAnnotion才是判断映射方法上面
            有没有贴注解
         */
        return parameter.getParameterType() == UserInfo.class && parameter.hasParameterAnnotation(UserParams.class);
        //return parameter.getParameterType() == UserInfo.class && parameter.hasMethodAnnotation(UserParams.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer
            , NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

        //获取token,得到请求头对象
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = request.getHeader("token");

        //返回用户对象
        UserInfo userInfo = userInfoRedisService.getUserByToken(token);
        return userInfo;
    }
}
